/**
 * 搜索直播页
 * page搜索
 */
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/bloc/live/search.dart';

import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/models/SearchModel.dart';
import 'package:qgchat/states/states_model/index.dart';
import 'package:qgchat/widgets/avatar.dart';

class Search extends StatefulWidget {
  Search({Key key}) : super(key: key);

  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {
  final widgetBloc = SearchBloc();

  @override
  void initState() {
    super.initState();
    if (mounted) {
      widgetBloc.init();
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<SearchBloc>(
      bloc: widgetBloc,
      child: Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(px(88)),
          child: AppBar(
            backgroundColor: col("fafafa"),
            centerTitle: false,
            title: Container(
              height: px(72),
              child: _SearchAppBarbuild(),
            ),
          ),
        ),
        body: StreamBuilder(
          stream: widgetBloc.outAlreadyStream,
          initialData: widgetBloc.alreadySearchStatus,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.data) {
              return _SearchResult();
            } else {
              return _SearchBuild();
            }
          },
        ),
      ),
    );
  }
}

class _SearchAppBarbuild extends StatelessWidget {
  _SearchAppBarbuild({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 正在搜索样式
    Widget onSearchWidget = Container(
      width: px(34),
      height: px(34),
      margin: EdgeInsets.only(left: px(17)),
      child: CircularProgressIndicator(
        strokeWidth: px(3),
      ),
    );

    // 没在搜索样式
    Widget offSearchWidget = Container(
      width: px(34),
      height: px(34),
      margin: EdgeInsets.only(left: px(17)),
      child: ImageIcon(
        AssetImage("assets/images/icon/search.png"),
        color: col("838383"),
        size: px(34),
      ),
    );

    final SearchBloc bloc = BlocProvider.of<SearchBloc>(context);
    return StreamBuilder<bool>(
      stream: bloc.outTextFieldStream,
      initialData: bloc.onSearchStatus,
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        return CupertinoTextField(
          controller: bloc.searchC,
          onSubmitted: bloc.onSubmitted,
          placeholder: '可以输入主播昵称',
          cursorColor: col("c471f5"),
          prefix: snapshot.data ? onSearchWidget : offSearchWidget,
          decoration: BoxDecoration(
            color: col("efefef"),
            borderRadius: BorderRadius.circular(px(20)),
          ),
        );
      },
    );
  }
}

// 未搜索时
class _SearchBuild extends StatelessWidget {
  _SearchBuild({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final SearchBloc bloc = BlocProvider.of<SearchBloc>(context);

    // 生成标题
    Widget titleHandle(title) {
      return Container(
        margin: EdgeInsets.only(top: px(50)),
        padding: EdgeInsets.symmetric(horizontal: px(30)),
        child: Text(
          title,
          style: TextStyle(
            color: col("303133"),
            fontSize: px(26),
            fontWeight: FontWeight.bold,
          ),
        ),
      );
    }

    // 未关注按钮样式
    Widget followBtnStyle(int id) {
      return Container(
        width: px(120),
        height: px(60),
        child: FlatButton(
          onPressed: () => bloc.follow(id),
          color: col("ffb240"),
          padding: EdgeInsets.all(0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(
              sp(40),
            ),
          ),
          child: Text(
            "关注",
            style: TextStyle(
              color: Colors.white,
              fontSize: px(26),
            ),
          ),
        ),
      );
    }

    // 已关注按钮样式
    Widget notFollowBtnStyle(SearchModel item) {
      return Container(
        width: px(120),
        height: px(60),
        child: FlatButton(
          onPressed: () {
            showCupertinoModalPopup(
              context: context,
              builder: (BuildContext context) {
                return CupertinoActionSheet(
                  title: Text(
                    "是否取消关注${item.memberNickname}",
                    style: TextStyle(
                      color: col("303133"),
                      fontSize: px(28),
                    ),
                  ),
                  cancelButton: CupertinoActionSheetAction(
                    onPressed: () => Navigator.pop(context),
                    child: Text("取消"),
                  ),
                  actions: <Widget>[
                    CupertinoActionSheetAction(
                      onPressed: () {
                        bloc.cancelfollow(item.id, item.memberNickname);
                        Navigator.pop(context);
                      },
                      child: Text(
                        "取消关注",
                        style: TextStyle(
                          color: col("fc3d39"),
                          fontSize: px(40),
                        ),
                      ),
                    )
                  ],
                );
              },
            );
          },
          color: col("edeff2"),
          padding: EdgeInsets.all(0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(
              sp(40),
            ),
          ),
          child: Text(
            "已关注",
            style: TextStyle(
              color: col("303133"),
              fontSize: px(26),
            ),
          ),
        ),
      );
    }

    // 单个主播
    Widget anchor(context, SearchModel item) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: px(30)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Avatar(
              item.memberHead,
              true,
              token: item.memberToken,
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(left: px(20)),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      width: 1,
                      color: col("edeff2"),
                    ),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: px(370),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Container(
                                margin: EdgeInsets.only(right: px(20)),
                                child: Text(
                                  '${item.memberNickname}',
                                  style: TextStyle(
                                    color: col("303133"),
                                    fontSize: px(28),
                                  ),
                                ),
                              ),
                              Text(
                                'ID: ${item.id}',
                                style: TextStyle(
                                  color: col("bfc2cc"),
                                  fontSize: px(24),
                                ),
                              ),
                            ],
                          ),
                          Container(
                            margin: EdgeInsets.only(top: px(15)),
                            child: Text(
                              "${item.anchorSign ?? "暂无个性签名"}",
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: col("909399"),
                                fontSize: px(26),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    stateBuilder(context, 'user', (UserState user) {
                      if (user.info.memberType == 1) {
                        return Container();
                      } else {
                        return item.follow != 1
                            ? followBtnStyle(item.id)
                            : notFollowBtnStyle(item);
                      }
                    }),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    }

    return ListView(
      children: <Widget>[
        titleHandle("推荐"),
        StreamBuilder<List<SearchModel>>(
          stream: bloc.outFateforStream,
          builder: (
            BuildContext context,
            AsyncSnapshot<List<SearchModel>> snapshot,
          ) {
            return Container(
              child: Column(
                children: bloc.youyuan.map((item) {
                  return Container(
                    height: px(170),
                    child: anchor(context, item),
                  );
                }).toList(),
              ),
            );
          },
        ),
        titleHandle("历史搜索"),
        StreamBuilder(
          stream: bloc.outHistoryStream,
          builder: (
            BuildContext context,
            AsyncSnapshot snapshot,
          ) {
            if (snapshot.hasData) {
              return Container(
                padding: EdgeInsets.symmetric(
                  horizontal: px(15),
                  vertical: px(15),
                ),
                child: Wrap(
                  spacing: px(0),
                  runSpacing: px(15),
                  children: snapshot.data.map<Widget>((item) {
                    return GestureDetector(
                      onTapUp: (test) => bloc.onSubmitted(item),
                      child: Container(
                        height: px(60),
                        margin: EdgeInsets.symmetric(horizontal: px(15)),
                        decoration: BoxDecoration(
                          color: col("666666"),
                          borderRadius: BorderRadius.all(
                            Radius.circular(px(30)),
                          ),
                        ),
                        padding: EdgeInsets.symmetric(
                          horizontal: px(30),
                          vertical: px(10),
                        ),
                        child: Text(
                          "$item",
                          style: TextStyle(
                            color: Colors.white,
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              );
            } else {
              return Container();
            }
          },
        ),
      ],
    );
  }
}

// 搜索时
class _SearchResult extends StatelessWidget {
  const _SearchResult({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final SearchBloc bloc = BlocProvider.of<SearchBloc>(context);

    final Widget title = Container(
      margin: EdgeInsets.only(top: px(50)),
      padding: EdgeInsets.symmetric(horizontal: px(30)),
      child: Text(
        '搜索结果',
        style: TextStyle(
          color: col("303133"),
          fontSize: px(26),
          fontWeight: FontWeight.bold,
        ),
      ),
    );

    // 未关注按钮样式
    Widget followBtnStyle(int id) {
      return Container(
        width: px(120),
        height: px(60),
        child: FlatButton(
          onPressed: () => bloc.follow(id),
          color: col("ffb240"),
          padding: EdgeInsets.all(0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(
              sp(40),
            ),
          ),
          child: Text(
            "关注",
            style: TextStyle(
              color: Colors.white,
              fontSize: px(26),
            ),
          ),
        ),
      );
    }

    // 已关注按钮样式
    Widget notFollowBtnStyle(SearchModel item) {
      return Container(
        width: px(120),
        height: px(60),
        child: FlatButton(
          onPressed: () {
            showCupertinoModalPopup(
              context: context,
              builder: (BuildContext context) {
                return CupertinoActionSheet(
                  title: Text(
                    "是否取消关注${item.memberNickname}",
                    style: TextStyle(
                      color: col("303133"),
                      fontSize: px(28),
                    ),
                  ),
                  cancelButton: CupertinoActionSheetAction(
                    onPressed: () => Navigator.pop(context),
                    child: Text("取消"),
                  ),
                  actions: <Widget>[
                    CupertinoActionSheetAction(
                      onPressed: () {
                        bloc.cancelfollow(item.id, item.memberNickname);
                        Navigator.pop(context);
                      },
                      child: Text(
                        "取消关注",
                        style: TextStyle(
                          color: col("fc3d39"),
                          fontSize: px(40),
                        ),
                      ),
                    )
                  ],
                );
              },
            );
          },
          color: col("edeff2"),
          padding: EdgeInsets.all(0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(
              sp(40),
            ),
          ),
          child: Text(
            "已关注",
            style: TextStyle(
              color: col("303133"),
              fontSize: px(26),
            ),
          ),
        ),
      );
    }

    // 单个主播
    Widget anchor(context, SearchModel item) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: px(30)),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Avatar(
              item.memberHead,
              true,
              token: item.memberToken,
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.only(left: px(20)),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      width: 1,
                      color: col("edeff2"),
                    ),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      width: px(370),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Container(
                                margin: EdgeInsets.only(right: px(20)),
                                child: Text(
                                  '${item.memberNickname}',
                                  style: TextStyle(
                                    color: col("303133"),
                                    fontSize: px(28),
                                  ),
                                ),
                              ),
                              Text(
                                'ID: ${item.id}',
                                style: TextStyle(
                                  color: col("bfc2cc"),
                                  fontSize: px(24),
                                ),
                              ),
                            ],
                          ),
                          Container(
                            margin: EdgeInsets.only(top: px(15)),
                            child: Text(
                              "${item.anchorSign ?? "暂无个性签名"}",
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: col("909399"),
                                fontSize: px(26),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    stateBuilder(context, 'user', (UserState user) {
                      if (user.info.memberType == 1) {
                        return Container();
                      } else {
                        return item.follow != 1
                            ? followBtnStyle(item.id)
                            : notFollowBtnStyle(item);
                      }
                    }),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    }

    return ListView(
      children: <Widget>[
        title,
        StreamBuilder<List<SearchModel>>(
          stream: bloc.outSearchStream,
          initialData: [],
          builder: (
            BuildContext context,
            AsyncSnapshot<List<SearchModel>> snapshot,
          ) {
            return Column(
              children: bloc.sousuo.map<Widget>((f) {
                return Container(
                  height: px(170),
                  child: anchor(context, f),
                );
              }).toList(),
            );
          },
        ),
      ],
    );
  }
}
